package org.itzixi.netty.utils;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.util.Properties;

@Slf4j
public class CuratorConfig {

    private static volatile CuratorFramework client;


    private static CuratorFramework init(){
        final Properties properties = PropertiesUtils.getInstance();
        int sleepMsBetweenRetry = Integer.parseInt(properties.getProperty("zookeeper.sleepMsBetweenRetry"));
        int maxRetries = Integer.parseInt(properties.getProperty("zookeeper.maxRetries"));
        int connTimeoutMs = Integer.parseInt(properties.getProperty("zookeeper.connTimeoutMs"));
        int sessionTimeoutMs = Integer.parseInt(properties.getProperty("zookeeper.sessionTimeoutMs"));
        String addr = properties.getProperty("server.addr");
        String port = properties.getProperty("zookeeper.port");
        String namespace = properties.getProperty("zookeeper.namespace");
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(sleepMsBetweenRetry, maxRetries);

        try {
            client = CuratorFrameworkFactory.builder()
                    .retryPolicy(retryPolicy)
                    .connectionTimeoutMs(connTimeoutMs)
                    .sessionTimeoutMs(sessionTimeoutMs)
                    .namespace(namespace)
                    .connectString(addr + StrUtil.COLON + port)
                    .build();
        } catch (Exception e) {
            log.error("获取本机IP失败：{},{}", e, e.getMessage());
            throw new RuntimeException(e);
        }
        client.start();
        return client;

    }

    public static CuratorFramework getClient(){
        if (client == null){
            synchronized (CuratorConfig.class){
                if (client == null){
                    client = init();
                }
            }
        }
        return client;
    }





}
